package com.itheima.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

/**
 * @date: 2022/11/21 9:59
 * @author: linying
 */
@Configuration
public class CorsConfig {


    /**
     * 跨域配置
     *
     * @return
     */
    private CorsConfiguration corsConfiguration() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        // 允许所有请求头通过
        corsConfiguration.addAllowedHeader("*");
        // 允许所有请求方法通过
        corsConfiguration.addAllowedMethod("*");
        // 允许所有请求来源通过
        corsConfiguration.addAllowedOrigin("*");
        return corsConfiguration;
    }

    /**
     * 跨域过滤器
     *
     * @return
     */
    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", corsConfiguration());
        return new CorsFilter(source);
    }

}
